package cn.com.fuhuitong.main.goods.ui.activity

import android.Manifest
import android.content.Intent
import android.net.Uri
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.lifecycle.Observer
import cn.com.fuhuitong.app.AppConstance
import cn.com.fuhuitong.aroute.ARouteConstance
import cn.com.fuhuitong.base.EmptyContent
import cn.com.fuhuitong.http.HttpResponseStatus
import cn.com.fuhuitong.main.base.ViewModeActivity
import cn.com.fuhuitong.main.goods.adpter.GVT
import cn.com.fuhuitong.main.goods.adpter.GoodsBottomAdapter
import cn.com.fuhuitong.main.goods.adpter.GoodsContentAdapter
import cn.com.fuhuitong.main.goods.entity.GoodsDetailsEntity
import cn.com.fuhuitong.main.goods.entity.GoodsSpecsEntity
import cn.com.fuhuitong.main.goods.popup.GoodsSpecsPopupWindow
import cn.com.fuhuitong.main.goods.vm.GoodsViewModel
import com.alibaba.android.arouter.facade.annotation.Autowired
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.vlayout.DelegateAdapter
import com.alibaba.android.vlayout.layout.SingleLayoutHelper
import com.alibaba.android.vlayout.layout.StickyLayoutHelper
import cn.com.fuhuitong.R
import cn.com.fuhuitong.entity.CartState
import cn.com.fuhuitong.entity.MainBean
import cn.com.fuhuitong.main.access.ui.activity.AccessActivity
import cn.com.fuhuitong.main.order.entity.SubmitConfirmEntity
import cn.com.fuhuitong.main.order.entity.SubmitConfirmGoods
import cn.com.fuhuitong.utils.JsonUtils
import com.alibaba.android.arouter.launcher.ARouter
import com.blankj.utilcode.util.LogUtils
import com.tbruyelle.rxpermissions2.RxPermissions
import kotlinx.android.synthetic.main.activity_goods_details.*
import org.greenrobot.eventbus.EventBus

@Route(path = ARouteConstance.ACTIVITY_URL_GOODS_DETAILS)
class GoodsDetailsActivity : ViewModeActivity<GoodsViewModel>() {

    enum class Action {
        SPECS, ADD_CART, BUY_NOW
    }

    private var action: Action = Action.SPECS

    @Autowired(name = AppConstance.BUNDLE_GOODS_ID)
    @JvmField
    var goodsId: Int = 0

    @Autowired(name = AppConstance.BUNDLE_GOODS_MEMBER)
    @JvmField
    var isMember: Boolean = false

    override fun viewModel(): GoodsViewModel = createViewModel()

    override val layoutResId: Int
        get() = R.layout.activity_goods_details

    override fun initView() {
        image_goods_back.setOnClickListener {
            this.finish()
        }

        this.initViewRecyclerAdapter(recycler_goods_details, arrayOf(GVT.GOODS_DETAILS.ordinal))

        delegateAdapter.addAdapters(mutableListOf<DelegateAdapter.Adapter<*>>(
            initViewGoodsContentAdapter().apply {
                goodsContentAdapter = this
            }, initViewGoodsBottomAdapter().apply {
                goodsBottomAdapter = this
            }
        ))

        goodsContentAdapter.setOnItemChildClickListener { view, _, detailsEntity ->
            when (view.id) {
                R.id.text_goods_details_specs -> {
                    this.action = Action.SPECS
                    if (detailsEntity.is_specifications == 1) {
                        viewModel.goodsSpecs(goodsId)
                    } else {
                        initViewGoodsSpecsPopupWindow(this.action, detailsEntity)
                            .showPopupWindow()
                    }
                }
                R.id.text_goods_details_group_name -> {
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_MEMBER)
                        .withInt(AppConstance.BUNDLE_MEMBER_ACTION, 2)
                        .navigation()
                }
            }
        }

        goodsBottomAdapter.setOnItemChildClickListener { view, _, detailsEntity ->
            when (view.id) {
                R.id.text_goods_details_add_cart, R.id.text_goods_details_buy_now -> {
                    this.action = if (view.id == R.id.text_goods_details_add_cart)
                        Action.ADD_CART else Action.BUY_NOW
                    if (detailsEntity.is_specifications == 1) {
                        viewModel.goodsSpecs(goodsId)
                    } else {
                        initViewGoodsSpecsPopupWindow(this.action, detailsEntity)
                            .showPopupWindow()
                    }
                }
                R.id.text_goods_details_service -> {

                    val rxPermission = RxPermissions(this)
                    rxPermission.request(Manifest.permission.CALL_PHONE)
                        .subscribe {
                            if (it) {
                                viewModel.configValuePhone(arrayOf("customer_service_mobile"))
                            } else {
                                toast("请到设置中开启权限")
                            }
                        }
                }
                R.id.text_goods_details_cart -> {
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_CART)
                        .navigation()
                }
            }
        }

        item_goods_details_collect.setOnClickListener {
            viewModel.addGoodsCollection(goodsId)
        }
    }

    private lateinit var goodsDetailsEntity: GoodsDetailsEntity
    private var groupName: String = ""

    override fun initViewMode() {

        viewModel.goodsDetailsDataLiveData.observe(this, Observer { response ->
            handlerResponseEmpty(
                status = response.status, message = response.statusTip,
                length = if (response.response?.data != null) 1 else 0,
                emptyContent = EmptyContent("去逛逛", "暂无数据")
            )
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let { detailsEntity ->
                detailsEntity.group_name = groupName
                this.updateAdapter(detailsEntity)
            }
        })

        viewModel.goodsSpecsDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.let { specs ->
                initViewGoodsSpecsPopupWindow(this.action, goodsDetailsEntity, specs)
                    .showPopupWindow()
            }
        })

        viewModel.goodsAddCartDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "添加成功")
            EventBus.getDefault().post(
                MainBean(type = CartState.ADD, data = null)
            )
        })

        viewModel.addGoodsCollectionDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            toast(response.response?.msg ?: "添加成功")
        })

        viewModel.configDataLiveData.observe(this, Observer { response ->
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.goods_url_text_family?.let {
                goodsDetailsEntity.group_name = it
                goodsContentAdapter.setAddDataNew(mutableListOf(goodsDetailsEntity))
            }
        })

        viewModel.configPhoneDataLiveData.observe(this, Observer { response ->
            handlerResponseLoading(response.status, response.statusTip)
            if (response.status != HttpResponseStatus.Status.SUCCESS)
                return@Observer
            response.response?.data?.customer_service_mobile?.let { mobile ->

                val builder = AlertDialog.Builder(this)
                    .setTitle("联系客服")
                    .setMessage(mobile)
                    .setPositiveButton("确定") { dialog, which ->
                        dialog.cancel()
                        val intent = Intent(Intent.ACTION_CALL);
                        val data = Uri.parse("tel:${mobile}");
                        intent.data = data
                        startActivity(intent)
                    }
                    .setNegativeButton("取消") { dialog, which ->
                        dialog.cancel()
                    }
                builder.show()
            }
        })
    }

    override fun initData() {
        viewModel.goodsDetails(goodsId)
    }

    override fun onResume() {
        super.onResume()
    }

    override fun onNewIntent(intent: Intent?) {
        super.onNewIntent(intent)
        setIntent(intent)
        goodsId = intent?.getIntExtra(AppConstance.BUNDLE_GOODS_ID, 0) ?: 0
        isMember = intent?.getBooleanExtra(AppConstance.BUNDLE_GOODS_MEMBER, false) ?: false
        initData()
    }

    private fun updateAdapter(
        goodsDetailsEntity: GoodsDetailsEntity,
        goodsSpecsEntity: GoodsSpecsEntity? = null
    ) {
        this.goodsDetailsEntity = goodsDetailsEntity
        this.goodsDetailsEntity.specifications = goodsSpecsEntity
        this.goodsContentAdapter.setAddDataNew(mutableListOf(this.goodsDetailsEntity))
        this.goodsBottomAdapter.setAddDataNew(mutableListOf(this.goodsDetailsEntity))
        this.viewModel.configValue(arrayOf("goods_url_text_family"))

        item_goods_details_collect.visibility = View.VISIBLE
        goodsBottomAdapter.isMember = isMember
    }


    /**
     * 初始化物品详情内容适配器
     * */
    private lateinit var goodsContentAdapter: GoodsContentAdapter
    private fun initViewGoodsContentAdapter(): GoodsContentAdapter {
        val helper = SingleLayoutHelper()
        return GoodsContentAdapter(this, helper)
    }

    /**
     * 初始化物品详情底部适配器
     * */
    private lateinit var goodsBottomAdapter: GoodsBottomAdapter
    private fun initViewGoodsBottomAdapter(): GoodsBottomAdapter {
        val helper = StickyLayoutHelper(false)
        return GoodsBottomAdapter(this, helper)
    }

    private fun initViewGoodsSpecsPopupWindow(
        action: Action, detailsEntity: GoodsDetailsEntity,
        specsEntity: MutableList<GoodsSpecsEntity> = mutableListOf()
    )
            : GoodsSpecsPopupWindow {
        return GoodsSpecsPopupWindow(this, isMember) { action, entity ->

            this.updateAdapter(detailsEntity, entity)

            when (action) {
                Action.SPECS -> {

                }
                Action.ADD_CART -> {
                    viewModel.goodsAddCart(
                        detailsEntity.id.toString(), entity.count.toString(), entity.id.toString()
                    )
                }
                Action.BUY_NOW -> {
                    val submitConfirmEntity = SubmitConfirmEntity(
                        arrayListOf(
                            SubmitConfirmGoods(
                                this.goodsDetailsEntity.id.toString(),
                                this.goodsDetailsEntity.specifications?.count.toString(),
                                this.goodsDetailsEntity.specifications?.id.toString()
                            )
                        )
                    )
                    ARouter.getInstance().build(ARouteConstance.ACTIVITY_URL_ORDER_SUBMIT)
                        .withSerializable(AppConstance.BUNDLE_SUBMIT_CONFIRM, submitConfirmEntity)
                        .navigation()
                }
            }
        }
            .apply {
                initDataPopupWindow(action, detailsEntity, specsEntity)
            }
    }
}